package com.cybertron.ironhide.spider.jms.listener;

import java.io.IOException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cybertron.ironhide.spider.Settings;
import com.cybertron.ironhide.spider.SpiderExecutor;
import com.cybertron.ironhide.spider.domain.SeedUrl;
import com.cybertron.ironhide.spider.json.JacksonObjectMapper;

@Component
public class SeedUrlMessageListener implements MessageListener {

	private final static Logger logger = Logger
			.getLogger(SeedUrlMessageListener.class);

	@Autowired(required = false)
	private SpiderExecutor executor;

	@Autowired(required = false)
	private JacksonObjectMapper jacksonObjectMapper;

	@Override
	public void onMessage(Message message) {
		TextMessage msg = (TextMessage) message;
		try {
			logger.info("receive msg.....");
			SeedUrl seedUrl = jacksonObjectMapper.readValue(msg.getText(),
					SeedUrl.class);
			if (seedUrl != null) {
				executor.run(seedUrl);
				logger.info("spider name " + Settings.SPIDER_ID
						+ "  execute task.....  " + msg.getText());
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}
